<?php


namespace App\Model\Logic;


use Elasticsearch\ClientBuilder;
use Swoftx\Elasticsearch\CoroutineHandler;

class ElasticSearchLogic
{

    public $client;

    public function __construct($host = null)
    {
        $handler = new CoroutineHandler([
            'timeout' => 2
        ]);
        $host = $host ? $host : env('VAFFLE_ELASTICSEARCH_HOST','172.100.10.5');
        if(!filter_var($host, FILTER_VALIDATE_IP)){
            $host = $host . ":443";
        }
        $hosts = array($host);
        $this->client = ClientBuilder::create()
            ->setHosts($hosts)
            ->setHandler($handler)
            ->build();

    }


    /**
     * ES 搜索
     * @param $params
     * @return array
     */
    public function search($params)
    {
        return $this->client->search($params);
    }


    /**
     * ES 统计
     * @param $params
     * @return array
     */
    public function count($params)
    {
        return $this->client->count($params);
    }


    /**
     * ES 搜索
     * @param $params
     * @return array
     */
    public function index($params)
    {
        return $this->client->index($params);
    }

    /**
     * Create操作
     * @param $params
     * @return mixed
     */
    public function create($params)
    {
        return $this->client->indices()->create($params);
    }

    /**
     * update操作
     * @param $params
     * @return mixed
     */
    public function update($params)
    {
        return $this->client->update($params);
    }

    /**
     * delete操作
     * @param $params
     * @return mixed
     */
    public function delete($params)
    {
        return $this->client->delete($params);
    }


    /**
     * 根据doc的ID 获取es 记录
     * @param $index
     * @param $type
     * @param $shop_id
     * @return array|bool
     */
    public function getItemById($index, $type, $doc_id)
    {
        if(!$index || !$type || !$doc_id)
        {
            return false;
        }

        $params = [
            'index' => $index,
            'type' => $type,
            "id" =>  (int) $doc_id
        ];

        try {
            $result = $this->client->get($params);
        } catch (\Exception $e) {
            return [];
        }
        return $result['_source'];
    }

    public function updateItemById($id, $data, $index, $type)
    {
        $params = [
            'index' => $index,
            'type' => $type,
            'id'   => $id,
            'body' => [
                'doc' => $data
            ]
        ];
        $this->client->update($params);
    }

}